<template>
	<view class="setting1">
		<view class="nav_top left">
			<view class="left">
				<text v-if="lang==0">
					软件版本：
				</text>
				<text v-if="lang==1">
					Version：
				</text>{{data.software_vision}}
			</view>
			<view class="right">
				<text v-if="lang==0">
					硬件版本：
				</text>
				<text v-if="lang==1">
					Hardware：
				</text>
				{{data.m_hardware_vision}}
			</view>
		</view>


	
		<view class="nav_menus left">
			<view class="titie_bottom">
				<view class="titie_top">
					<view class="top_left left">
					
						<text v-if="lang==0">
							学习状态
						</text>
						<text v-if="lang==1">
							Learning status
						</text>
					</view>
					
				</view>
				<view class="titie_body"  style="height: 340rpx;">
					<view class="titie_body_left" >
						<uv-checkbox-group v-model="checkboxValue" label-color="#ffffff"	  placement="column">
									<uv-checkbox 
										:customStyle="{marginBottom: '8px'}" 
										v-for="(item, index) in checkboxList" 
										:key="index" :label="item.name" 
										:name="item.name"
									></uv-checkbox>
								</uv-checkbox-group>
					</view>
					<view class="titie_body_right">
						<view>
							母线电流(A)
						</view>
						<view class="right">
							<input disabled  v-model="muxian_a.toFixed(1)" type="text">
						</view>
					</view>
					
					<view class="titie_body_right">
						<view>
							相线电流(A)
						</view>
						<view class="right">
							<input disabled v-model="xiangxian.toFixed(1)" type="text">
						</view>
					</view>
					
					<view class="titie_body_right">
						<view>
							速度(RPM)
						</view>
						<view class="right">
							<input disabled v-model="zhuansu" type="text">
						</view>
					</view>
					
				</view>
			</view>
		</view>
		<view class="nav_menus left">
			<view class="titie_bottom">
				<view class="titie_top">
					<view class="top_left left">
					
						<text v-if="lang==0">
							学习进度
						</text>
						<text v-if="lang==1">
							rate  of learning
						</text>
					</view>
					
				</view>	
				<view class="titie_body" style="height: 60rpx;">
						<uv-line-progress   :percentage="percent" height="16px" inactiveColor="#6174AD" activeColor="#507afe"></uv-line-progress>
				</view>
			</view>
		</view>
		
		<view class="" >
			<view class="bomt"
			style="margin-bottom: 7rpx;"
			 :style="percent==0||percent>=100?'':'background:#475165;color:#cecece'"
			 >
				<view class="bom_left" @click="handleWriteValues()">
					
					<text v-if="lang==0">
						开始学习
					</text>
					<text v-if="lang==1">
						开始学习
					</text>
				</view>
			</view>
		</view>
		
		<view class="nav_menus left">
			<view class="titie_top">
				<view class="top_left left">
				
					<text v-if="lang==0">
						学习结果
					</text>
					<text v-if="lang==1">
						Learning outcomes
					</text>
				</view>
				
			</view>	
			<view class="titie_bottom">
				<view class="titie_body">
					<view class="body_line">
						<view class="left">
							
							<text v-if="lang==0">
									相移角(°)
							</text>
							<text v-if="lang==1">
								Phase shift angle (°)
							</text>
						</view>
						<view class="right">
							<input disabled v-model="xiangyijiao" type="text">
						</view>
					</view>
				</view>
				<view class="titie_body_line">
					
				</view>
				
				<view class="titie_body">
					<view class="body_line">
						<view class="left">
							
							<text v-if="lang==0">
									电机内阻Rs(ohm)
							</text>
							<text v-if="lang==1">
								Rs(ohm)
							</text>
						</view>
						<view class="right">
								<input  disabled   v-model="neizu.toFixed(1)" type="text">
						</view>
					</view>
				</view>
				
				<view class="titie_body_line">
					
				</view>
				
				<view class="titie_body">
					<view class="body_line">
						<view class="left">
							
							<text v-if="lang==0">
								D轴电感Ld(uH)
							</text>
							<text v-if="lang==1">
								Ld(uH)
							</text>
						</view>
						<view class="right">
								<input disabled v-model="d_gan.toFixed(1)" type="text">
						</view>
					</view>
				</view>
				
				<view class="titie_body_line">
					
				</view>
				<view class="titie_body">
					<view class="body_line">
						<view class="left">
							
							<text v-if="lang==0">
								Q轴电感Lq(uH)
							</text>
							<text v-if="lang==1">
								Lq(uH)
							</text>
						</view>
						<view class="right">
								<input disabled  v-model="q_gan.toFixed(1)" type="text">
						</view>
					</view>
				</view>
				
				<view class="titie_body_line">
					
				</view>
				<view class="titie_body">
					<view class="body_line">
						<view class="left">
							
							<text v-if="lang==0">
								反电势Ke(Vrms/Krpm)
							</text>
							<text v-if="lang==1">
								Ke(Vrms/Krpm)
							</text>
						</view>
						<view class="right">
								<input disabled v-model="fanshe.toFixed(1)" type="text">
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="nav_menus left">
		
			<view class="titie_bottom">
				<view class="titie_body">
					<view class="body_line">
						<view class="left" @click="xh_openPicker()">
							
							<text v-if="lang==0">
								仪表协议
							</text>
							<text v-if="lang==1">
								Instrument protocol
							</text>
						</view>
						<view class="right">
							<input disabled  :value="xieyi_arr[xieyi]" type="text">
						</view>
					</view>
				</view>
			</view>
		</view>
		
		
	<!-- 	<view class="nav_menus left" v-show="">
		percent==0||percent>=100
		</view> -->
		<view class="" >
			<view class="bomt"
			 :style="percent==0||percent>=100?'':'background:#475165;color:#cecece'"
			 >
				<view class="bom_left" @click="qiehuan()">
					
					<text v-if="lang==0">
						电机正反转切换
					</text>
					<text v-if="lang==1">
						Forward/backward
					</text>
				</view>
			</view>
		</view>
	
	<!-- 
		
		<view class="" style="background: #19253E;">
			<view class="bomt">
				<view class="bom_left" @click="handleWriteValues()">
					
					<text v-if="lang==0">
						开始学习
					</text>
					<text v-if="lang==1">
						Start learning
					</text>
				</view>
			</view>
		</view> -->
		<view  style="width: 100%;height: 120rpx;float: left;"></view>
		
		<!-- <textarea style="background: #fff;color: #000" name="" v-model="log_data" id="" cols="30" rows="10"></textarea>
		 -->
		<tabbar :lang="lang" :current="1"></tabbar>
	</view>
</template>

<script>
var app = getApp();
import utils from "@/utils/util.js"
// import { setTimeout } from '../../../utils/mqtt'
const errorCode = {
  '-1': '已连接',
  10000: '未初始化蓝牙适配器',
  10001: '当前蓝牙适配器不可用',
  10002: '没有找到指定设备',
  10003: '连接失败',
  10004: '没有找到指定服务',
  10005: '没有找到指定特征值',
  10006: '当前连接已断开',
  10007: '当前特征值不支持此操作',
  10008: '其余所有系统上报的异常',
  10009: '系统版本低于 4.3 不支持 BLE',
  10010: '已连接',
  10011: '配对设备需要配对码',
  10012: '连接超时',
  10013: '连接 deviceId 为空或者是格式不正确',
}

export default {
  name: 'bluetooth',
  data() {
    return {
		log_data:"",
		s:0,
		checkboxValue: ['空闲'],
		// 基本案列数据
		checkboxList: [{
			name: '空闲',
			disabled: false
		}, {
			name: '运行',
			disabled: false
		}, {
			name: '完成',
			disabled: false
		},
		{
			name: '角度学习错误',
			disabled: false
		}, {
			name: '电阻电感学习错误',
			disabled: false
		}, {
			name: '反向电动势学习错误',
			disabled: false
		}],
		percent:0,
		user_type:0,
		lang:0,
		
		dianya:[
			[48,60,72,84,96,108]
		],
		jibie:[
			[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
		],
		
		boxTop: uni.getMenuButtonBoundingClientRect().top - 4 + 'px',
		boxRight: 375 - uni.getMenuButtonBoundingClientRect().left + 20 + 'px',
		boxHeight: uni.getMenuButtonBoundingClientRect().top + uni.getMenuButtonBoundingClientRect().height + 4 + 'px',
		banner: [
			{
				image: '../../../static/share2.png'
			},{
				image: '../../../static/share2.png'
			},{
				image: '../../../static/share2.png'
			}
		],
      // 是否初始化了蓝牙模块
      isInitBluetooth: false,
      // 是否搜索中
      isSearching: false,

      // 搜索到的设备列表
      deviceList: [],

      // 当前连接的蓝牙设备信息
      deviceInfo: {},
      // 当前连接的蓝牙设备的服务信息
      serviceInfo: {},
      // 支持 write 的特征值信息
      writeCharacteristicsInfo: {},
      // 支持 notify 或者 indicate 的特征值信息
      notifyCharacteristicsInfo: {},
	  is_yuancheng:0,
	  is_biao:0,
	  time_head:null,
	  che_xintiao:0,
	  h_i:0,
	  muxian_a:0,
	  xiangxian:0,
	  zhuansu:0,
	  h_f:0x00,
	  xiangyijiao:0,
	  neizu:0,
	  d_gan:0,
	  q_gan:0,
	  fanshe:0,
	  
	  xieyi:0,
	  xieyi_arr:["无一线通仪表","雅迪兼容协议"],
      data:{
		
	  }
    }
  },
  onHide(){
	  if(this.time_head){
	  	clearInterval(this.time_head)
	  }
	 
	 app.globalData.is_rw = 1;
	 uni.setStorageSync('dev_data', this.data);
  },
  onUnload() {
	  if(this.time_head){
	  	clearInterval(this.time_head)
	  }
   	console.log("mv")
	app.globalData.is_rw = 1;
	uni.setStorageSync('dev_data', this.data);
		
  },
 onShow() {
	
	  this.data = uni.getStorageSync('dev_data');
	
	 
	 this.show_on();
	
 },
  onLoad() {
		uni.hideTabBar();
 
		 app.globalData.is_rw = 1;
	    //获取特征值
	    // that.getBLEDeviceCharacteristics();
	    
	//handleConnectDevice
	//要去他的页面的
  },
  methods: {
	  qiehuan(){
		  if(this.percent>0 && this.percent<100){
			  return;
		  }
		  
		  if (app.globalData.connected != true) {
		  	if(this.lang==0){
		  		uni.showToast({
		  			title: '需要先连接蓝牙',
		  			icon:"none"
		  		})
		  	}else{
		  		uni.showToast({
		  			title: 'Bluetooth needs to be connected first',
		  			icon:"none"
		  		})
		  	}
		  	return;
		  }
		  
		//开始
		uni.showLoading({
			title: 'loading',
			mask:true
		});
		
		this.che_xintiao = 1;
		setTimeout(()=>{
			uni.onBLECharacteristicValueChange((res) => {
					const value = Array.prototype.map.call(new Uint8Array(res.value), (bit) => bit)
					console.log("正反转",value)
					console.log("正反转_str",this.$util.ab2hext_str(value))
					//参数结果？
					uni.hideLoading()
					if(this.lang==1){
						uni.showToast({
							title: 'Successfully edit',
							icon:"none"
						})
					}else{
						uni.showToast({
							title: '修改成功',
							icon:"none"
						})
					}
					
					this.get_home_data()
					this.che_xintiao = 0;
			})
		
			let values = [0xaa,0x0c,0x00, 0x10, 0x01, 0x07,
				 0x09,0x04,//相移角
				 0x00,0x00,//Q轴电感 * 0.1
				 0x00,0x00,//反电势 
			];
			console.log("发送数据结果")
			this.handleWriteValue_w(values);
		},300)
		  
	  },
	  xieyo_openPicker(type) {
	  		this.$refs.xieyi_picker.open();
	  },
	  show_on(){
		  
		app.globalData.is_rw = 1;
		 if(uni.getStorageSync('user_type')){
		 	this.user_type = uni.getStorageSync('user_type')
		 }
		 
		 this.is_yuancheng = app.globalData.is_yuancheng;
		
		 let lang = uni.getStorageSync('lang')
		
		this.lang = uni.getStorageSync('lang')
		
		if(this.lang == 1){
			uni.setNavigationBarTitle({
			         title: 'study'
			})
		}else{
			uni.setNavigationBarTitle({
			       title: '学习'
			})
		}
		 
		
		// let is_ok = uni.getStorageSync('is_ok');
		// console.log(is_ok,777777777,'加载..')
		// if(is_ok != 1){
			
		// }else{

		// }
		
		
		this.is_biao = 0;
		
		this.deviceList = uni.getStorageSync('deviceList');
		this.serviceInfo = uni.getStorageSync('serviceInfo');
		this.writeCharacteristicsInfo = uni.getStorageSync('writeCharacteristicsInfo');
		
		
		this.notifyCharacteristicsInfo = uni.getStorageSync('notifyCharacteristicsInfo');
		this.deviceInfo = uni.getStorageSync('deviceInfo');
			
			
		var that = this;
		var devid = this.deviceInfo.deviceId;//decodeURIComponent(options.deviceId);
		var devname = this.deviceInfo.name;//decodeURIComponent(options.name);
		var devserviceid = this.serviceInfo.uuid;//decodeURIComponent(options.serviceId);
		
		
		app.globalData.is_rw = 1;
		 if(uni.getStorageSync('user_type')){
		 	this.user_type = uni.getStorageSync('user_type')
		 }
		 

		
		this.is_yuancheng = app.globalData.is_yuancheng;
		
		
		this.lang = uni.getStorageSync('lang')
		
		if(this.lang == 1){
			uni.setNavigationBarTitle({
			         title: 'study'
			})
		}else{
			uni.setNavigationBarTitle({
			       title: '学习'
			})
		}
		 
		 
		 
		
		// let is_ok = uni.getStorageSync('is_ok');
		// console.log(is_ok,777777777,'加载..')
		// if(is_ok != 1){
			
		// }else{
			this.data = uni.getStorageSync('dev_data');
		// }
		
		
		
		this.is_biao = 0;
		
		this.deviceList = uni.getStorageSync('deviceList');
		this.serviceInfo = uni.getStorageSync('serviceInfo');
		this.writeCharacteristicsInfo = uni.getStorageSync('writeCharacteristicsInfo');
		
		
		this.notifyCharacteristicsInfso = uni.getStorageSync('notifyCharacteristicsInfo');
		this.deviceInfo = uni.getStorageSync('deviceInfo');
			
		if (app.globalData.connected == true) {
			
			this.get_jieguo();
			setTimeout(()=>{
				//发送读取
				if(this.time_head){
					clearInterval(this.time_head)
				}
				
				this.time_head = setInterval(()=>{
					console.log("是否学习111",this.che_xintiao)
					if(this.che_xintiao == 0){
						// this.get_home_data()
						this.heartbeat()
						// this.get_jieguo();
					}
				},300);
			},300)
		}	
		
	  },
		writeBLECharacteristicValue(buffer){
			
			
			uni.writeBLECharacteristicValue({
			  // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
			  deviceId: this.deviceInfo.deviceId,
			  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			  serviceId: this.serviceInfo.uuid,
			  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
			  
			  characteristicId: this.writeCharacteristicsInfo.uuid,
			  // 这里的value是ArrayBuffer类型
			  value: buffer,
			  writeType: 'writeNoResponse',
			  success(res) {
			    console.log('writeBLECharacteristicValue success', res.errMsg)
							 
			  },
			  fail(error) {
			    console.log('fail')
			    console.log(error)
				
							  
			  },
			})
		},

	handleWriteValues(){
		if (app.globalData.connected != true) {
			if(this.lang==0){
				uni.showToast({
					title: '需要先连接蓝牙',
					icon:"none"
				})
			}else{
				uni.showToast({
					title: 'Bluetooth needs to be connected first',
					icon:"none"
				})
			}
			return;
		}
			
			// uni.showLoading({
			// 	title: 'loading',
			// 	mask:true
			// });
			this.che_xintiao = 1;
			// setTimeout(()=>{
				this.handleWriteValue()
			// },300)

		
	},
	get_home_data(){
		uni.onBLECharacteristicValueChange((res) => {
			
		   const value = Array.prototype.map.call(new Uint8Array(res.value), (bit) => bit)
		   
		   
		   console.log("监听到的数据1",value)
		   console.log("监听到的数据 cl1",this.$util.ab2hext_str(value))
			
		   let checkpage = app.globalData.checkpage;
		   let lenth = this.$util.ab2hext_str(value).length;
		   console.log("长度"+lenth)
		   // app.globalData.mare_data = this.$util.ab2hext(value);
		   // this.cl_datas(app.globalData.mare_data);
		   
		   if(!checkpage){
			app.globalData.mare_data = this.$util.ab2hext(value);
			
			//是否有后续的值？
			if(lenth >= 24 && lenth<43){
				console.log("需要继续处理1？");
				//是否还有后须针  需要重新组合数据 最后再分割
				app.globalData.checkpage = 1;
			}else{
				console.log("直接处理？");
				//可以直接处理了
				this.cl_datas(app.globalData.mare_data);
			}
		   }else{
				
			let data1 = app.globalData.mare_data;
			app.globalData.mare_data = app.globalData.mare_data + this.$util.ab2hext(value);
		   //
			if(lenth > 24 && lenth<43){
				//等待处理
				console.log("需要继续处理2++？");
				app.globalData.checkpage++;
			}else{
				//可以处理
				console.log("不需要继续处理2？");
				this.cl_datas(app.globalData.mare_data);
			}
		   }
			// this.funReadPage(value)
		  // this.Rec_data_deal(value);
		})
	},
	cl_datas(){
		let cl_data = app.globalData.mare_data;
		app.globalData.checkpage = 0;
		app.globalData.mare_data = null;
				
		let hexString = cl_data; // 要分割的十六进制字符串
		let splitResult = []; // 存放分割结果的数组
		
		hexString.match(/.{2}/g).forEach((item) => {
						  splitResult.push(item);
		});
		
		console.log(splitResult,9797);
		
		 //故障
		
		 
		 console.log(972,splitResult[13]+splitResult[12])
		 
		 //母线电压 
		 this.muxian_v = parseInt(splitResult[13]+splitResult[12],16)*0.1;
		 console.log("muxian_v",this.muxian_v)	
		 //母线电流
		 this.muxian_a = parseInt(splitResult[15]+splitResult[14],16)*0.1-1500;
		 console.log("muxian_a",this.muxian_a)	
		
		 //电机转速
		 this.zhuansu = parseInt(splitResult[17]+splitResult[16],16)-20000;
		 console.log("zhuansu",this.zhuansu)	
		 
		
		 
		 
		 console.log("splitResult[19]+splitResult[18]",splitResult[19]+splitResult[18])
		 
		 //相电流   
		 this.xiangxian = parseInt(splitResult[19]+splitResult[18],16)*0.1-3000;
		 console.log("xiangxian",this.xiangxian)	
		
		 //弱磁电流
		 let ruoci = parseInt(splitResult[21]+splitResult[20],16)*0.1-3000;
		console.log("ruoci",this.ruoci)	
		/*
		"aa", "16", "00", "10", "01", "01", "40", "39", "00", "00",
		"00", "00", "33", "03", "99", "3a", "11", "4f", "44", "75",
		"30", "75", "52", "e6", "aa", "12", "01", "10", "de", "03",
		"58", "02", "5a", "00", "01", "83", "00", "00", "00", "00",
		"00", "00", "ac", "96"
		console.log("dianji",this.dianji)
		*/
		
//mos温度  
		this.mos = parseInt(splitResult[29]+splitResult[28],16)*0.1-60;
		console.log("mos",this.mos)	
		
		//电机温度
		this.dianji = parseInt(splitResult[31]+splitResult[30],16)*0.1-60;
		console.log("dianji",this.dianji)	
		
		//油门电压
		this.dianya = parseInt(splitResult[33]+splitResult[32],16)*0.1-60;
		console.log("dianya",this.dianya)	
	
	/**
	 ["aa", "16", "00", "10", "01", "01", "01", "13", "00", "00", 
	  "00", "00", "35", "03", "ca", "3a", "20", "4e", "b6", "75", 
	  "01", "75", "b3", "66", "aa", "12", "01", "10", "34", "03", 
	  "58", "02", "56", "00", "01", "a3", "00", "00", "00", "00",
	   "00", "00", "a6", "41"]
	 * 
*/
		//合并
		let hebing = this.$util.hebing_zijie(splitResult[34],splitResult[35])
		console.log("hebing",hebing);
		
		//运算得出值
		let hebing_cl = this.$util.get_bit(hebing,12,4)
		console.log("hebing_cl",hebing_cl);
		//学习进度
		
		this.percent = hebing_cl * 10;
		
		console.log("percent",this.percent);
		if(this.percent > 0){
			//空闲
			this.checkboxValue = ['运行']
		}
		
		if(this.percent == 100){
			//自学习完成 需要读取结果
			this.checkboxValue = ['完成']
			
			this.get_jieguo();
		}
		
		   //故障状态1
		   let guzhang_1 = this.$util.hebing_zijie(splitResult[8],splitResult[9])
		    //运算得出值
		   let guzhang_1_cl = this.$util.get_bit(guzhang_1,8,4)
		   console.log("guzhang_1_cl",guzhang_1_cl)
		   
		   let guzhang_2 = this.$util.hebing_zijie(splitResult[10],splitResult[11])
		    //运算得出值
		   let guzhang_2_cl = this.$util.get_bit(guzhang_2,7,1)
		   console.log("guzhang_1_cl",guzhang_1_cl)
		   
		//的
		if(guzhang_1_cl == 1){
			//有故障
			let sys_err = this.$util.get_bit(hebing,0,8)	
			console.log("sys_err",sys_err);
			if(sys_err == 0x09){
				this.checkboxValue = ['角度学习错误']
			}else if(sys_err == 0x0a){
				this.checkboxValue = ['电阻电感学习错误']
			}else if(sys_err == 0x0b){
				this.checkboxValue = ['反向电动势学习错误']
			}   
		}
		
	//   let cl_data = app.globalData.mare_data;
	//   app.globalData.checkpage = 0;
	//   app.globalData.mare_data = null;

	//   let hexString = cl_data; // 要分割的十六进制字符串
	//   let splitResult = []; // 存放分割结果的数组
	  
	//   hexString.match(/.{2}/g).forEach((item) => {
	// 	  splitResult.push(item);
	//   });
	  
	//   console.log(splitResult,9797);
	  
	//    //故障
	  
	   
	//    //故障状态1
	//    let guzhang_1 = this.$util.hebing_zijie(splitResult[9],splitResult[8])
	//     //运算得出值
	//    let guzhang_1_cl = this.$util.get_bit(guzhang_1,8,4)
	//    console.log("guzhang_1_cl",guzhang_1_cl)
	   
	//    let guzhang_2 = this.$util.hebing_zijie(splitResult[11],splitResult[10])
	//     //运算得出值
	//    let guzhang_2_cl = this.$util.get_bit(guzhang_2,7,1)
	//    console.log("guzhang_1_cl",guzhang_1_cl)
	
	//    console.log(972,splitResult[13]+splitResult[12])
	//    //母线电压 
	//    this.muxian_v = parseInt(splitResult[13]+splitResult[12],16)*0.1;
	//    console.log("muxian_v",this.muxian_v)	
	//    //母线电流
	//    this.muxian_a = parseInt(splitResult[15]+splitResult[14],16)*0.1-1500;
	//    console.log("muxian_a",this.muxian_a)	
	  
	//    //电机转速
	//    this.zhuansu = parseInt(splitResult[17]+splitResult[16],16)-20000;
	//    console.log("zhuansu",this.zhuansu)	
	   
	//    console.log("splitResult[19]+splitResult[18]",splitResult[19]+splitResult[18])
	   
	//    //相电流   
	//    this.xiangxian = parseInt(splitResult[19]+splitResult[18],16)*0.1-3000;
	//    console.log("xiangxian",this.xiangxian)	
	   
	//    //弱磁电流
	//    let ruoci = parseInt(splitResult[21]+splitResult[20],16)*0.1-3000;
	// 	console.log("ruoci",this.ruoci)	
		
	//    //mos温度  
	// 	this.mos = parseInt(splitResult[30]+splitResult[29],16)*0.1-60;
	// 	console.log("mos",this.mos)	
		
	// 	//电机温度
	// 	this.dianji = parseInt(splitResult[32]+splitResult[31],16)*0.1-60;
	// 	console.log("dianji",this.dianji)	
		
	// 	//油门电压
	// 	this.dianya = parseInt(splitResult[34]+splitResult[33],16)*0.1-60;
	// 	console.log("mos",this.dianya)	
		
	// 	//按位查询
	// 	console.log(splitResult[36],splitResult[35]);
		
	// 	//合并
	// 	let hebing = this.$util.hebing_zijie(splitResult[36],splitResult[35])
	// 	//运算得出值
	// 	let hebing_cl = this.$util.get_bit(hebing,8,4)
	// 	console.log("hebing",hebing_cl);
	// 	//学习进度
	// 	this.percent = hebing_cl * 10;
	// 	console.log("percent",this.percent);
	// 	if(this.percent > 0){
	// 		//空闲
	// 		this.checkboxValue = ['运行']
	// 	}
		
	// 	if(this.percent == 100){
	// 		//自学习完成 需要读取结果
	// 		this.checkboxValue = ['完成']
	// 		this.get_jieguo();
	// 	}
	// 	//的
	// 	if(guzhang_1_cl == 1){
	// 		//有故障
	// 		let sys_err = this.$util.get_bit(hebing,0,8)	
	// 		console.log("sys_err",sys_err);
	// 		if(sys_err == 0x09){
	// 			this.checkboxValue = ['角度学习错误']
	// 		}else if(sys_err == 0x0a){
	// 			this.checkboxValue = ['电阻电感学习错误']
	// 		}else if(sys_err == 0x0b){
	// 			this.checkboxValue = ['反向电动势学习错误']
	// 		}   
	// 	}
		
		// app.globalData.connected
	},
	get_jieguo(){
		this.che_xintiao = 1;
		setTimeout(()=>{
			uni.onBLECharacteristicValueChange((res) => {
					const value = Array.prototype.map.call(new Uint8Array(res.value), (bit) => bit)
					console.log("获取学习结果",value)
					console.log("获取学习结果_str",this.$util.ab2hext_str(value))
					//参数结果？
					this.jieguo_cl(this.$util.ab2hext(value));
					this.get_home_data()
					this.che_xintiao = 0;
					
			})
		
			let values = [0xaa,0x12,0x00, 0x10, 0x01, 0x05,
				 0x08,0x00,//相移角
				 0x05,0x00,//电机内阻
				 0x03,0x00,//D轴电感  * 0.1
				 0x04,0x00,//Q轴电感 * 0.1
				 0x06,0x00,//反电势 
				 0x08,0x01,//仪表协议 777777
			];
			console.log("发送数据结果")
			this.handleWriteValue_w(values);
		},400)
	},
	jieguo_cl(value){
		
		let hexString = value; // 要分割的十六进制字符串
		let splitResult = []; // 存放分割结果的数组
		hexString.match(/.{2}/g).forEach((item) => {
			 splitResult.push(item);
		});
		
		// 0x08,0x00,//相移角
		this.xiangyijiao = parseInt(splitResult[7]+splitResult[6],16) - 180;
		console.log("this.xiangyijiao",this.xiangyijiao)
		
		//0x05,0x00,//电机内阻
		this.neizu = parseInt(splitResult[9]+splitResult[8],16) * 0.1;
		console.log("this.neizu",this.neizu)
		
		//0x03,0x00,//D轴电感  * 0.1
		this.d_gan = parseInt(splitResult[11]+splitResult[10],16) * 0.1;
		console.log("this.d_gan",this.d_gan)
		
		//0x04,0x00,//Q轴电感 * 0.1
		this.q_gan = parseInt(splitResult[13]+splitResult[12],16) * 0.1;
		console.log("this.q_gan",this.q_gan)
		
		//0x06,0x00,//反电势 
		this.fanshe = parseInt(splitResult[15]+splitResult[14],16) * 0.1;
		console.log("this.fanshe",this.fanshe)
		
		//协议 77777
		this.xieyi = parseInt(splitResult[19]+splitResult[18],16) * 0.1;
		console.log("this.xieyi",this.xieyi)
	},
	handleWriteValue_w(values) {
		let that = this;
		//AA 0C 00 10 01 1F 00 00 00 00 00 00 DB 79 
		//0xdb, 0x79,
		// 0 - 255
		 let temp = this.$util.CRC16Modbus(values);
		 
		 
		 console.log("发送数据获取学习结果数据",temp)	
		 console.log("发送数据",this.$util.ab2hext_str(temp))	
			 
		 let strArray = new Uint8Array(temp)
		
		 const buffer = strArray.buffer
	
		// const buffer = new ArrayBuffer(1)
		// const dataView = new DataView(buffer)
		// dataView.setUint8(0, 0)
	
		// 向低功耗蓝牙设备特征值中写入二进制数据
		uni.writeBLECharacteristicValue({
		  // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
		  deviceId: this.deviceInfo.deviceId,
		  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
		  serviceId: this.serviceInfo.uuid,
		  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
		  characteristicId: this.writeCharacteristicsInfo.uuid,
		  // 这里的value是ArrayBuffer类型
		  value: buffer,
		  writeType: 'writeNoResponse',
		  success(res) {
			console.log("发送成功")
			console.log('writeBLECharacteristicValue success', res.errMsg)
			
		  },
		  fail(error) {
				uni.hideLoading();	
			console.log('fail')
			console.log(error)
		  
			if (error.errCode) {
			  uni.showToast({ title: errorCode[error.errCode], icon: 'none' })
			} else if (error.errMsg) {
			  uni.showToast({ title: error.errMsg, icon: 'none' })
			} else {
			  uni.showToast({ title: 'fail', icon: 'none' })
			}
		  
		  },
		})
	},
	heartbeat(){
		
	  let that = this;
		//AA 0C 00 10 01 1F 00 00 00 00 00 00 DB 79 
	   console.log("读秒归0")
		//0xdb, 0x79,
		// 0 - 255
		let h_i = this.h_i;
		if(h_i>=99){
			this.h_i = 0;
		}else{
			this.h_i++;
		}
		this.get_home_data();
		//0xaa,  0x0c,    0x00,    0x10,     0x01, 0x01
		//报文头	 报文长度   帧序列号	帧数据	设备id ，报文命令
		 let temp = this.$util.CRC16Modbus([
				0xaa,0x0c,0x00, 0x10, 0x01, 0x01, h_i, this.h_f, 0x00, 0x00, 0x00, 0x00
		 ]);
		 console.log("发送心跳",temp)		
		 let strArray = new Uint8Array(temp)
		
		 const buffer = strArray.buffer
	  
		// 向低功耗蓝牙设备特征值中写入二进制数据
		uni.writeBLECharacteristicValue({
		  // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
		  deviceId: this.deviceInfo.deviceId,
		  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
		  serviceId: this.serviceInfo.uuid,
		  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
		  characteristicId: this.writeCharacteristicsInfo.uuid,
		  // 这里的value是ArrayBuffer类型
		  value: buffer,
		  writeType: 'writeNoResponse',
		  success(res) {
			console.log("发送成功")
			console.log('writeBLECharacteristicValue success', res.errMsg)
		 
		  },
		  fail(error) {
				uni.hideLoading();	
			console.log('fail')
			console.log(error)
		  
			if (error.errCode) {
			  uni.showToast({ title: errorCode[error.errCode], icon: 'none' })
			} else if (error.errMsg) {
			  uni.showToast({ title: error.errMsg, icon: 'none' })
			} else {
			  uni.showToast({ title: 'fail', icon: 'none' })
			}
		  
		  },
		})
	},
    // 向低功耗蓝牙设备特征值中写入二进制数据
    handleWriteValue() {
		
		
		
		uni.onBLECharacteristicValueChange((res) => {
		
			const value = Array.prototype.map.call(new Uint8Array(res.value), (bit) => bit)
			console.log("开始学习监听到的值value",value,9999999) //学习结束 
			console.log("开始学习监听到的值value_str",this.$util.ab2hext_str(value),9999999) //学习结束 
		
			this.che_xintiao = 0;
			this.get_home_data()
		})
		
		//循环的数据
		
		let h_i = this.h_i;
		if(h_i>=99){
			this.h_i = 0;
		}else{
			this.h_i++;
		}
		
     //  let strArray = new Uint8Array([
     //    0xaa, 0x0c, 0x00, 0x10, 0x01, 0x07, 0x01,  parseInt(this.h_i,16), 0x00, 0x00, 0x00, 0x00])
     
	 let temp = this.$util.CRC16Modbus([
	 		 0xaa, 0x0c, 0x00, 0x10, 0x01, 0x07, 0x01,  h_i, 0x00, 0x00, 0x00, 0x00
	 ]);
	  let strArray = new Uint8Array(temp)
	  const buffer = strArray.buffer	
	  
	   console.log("开始学习发送  value",strArray)
	   console.log("开始学习发送  value_str",this.$util.ab2hext_str(strArray))
	  this.che_xintiao = 0;
      // 向低功耗蓝牙设备特征值中写入二进制数据
      uni.writeBLECharacteristicValue({
        // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId: this.deviceInfo.deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: this.serviceInfo.uuid,
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId: this.writeCharacteristicsInfo.uuid,
        // 这里的value是ArrayBuffer类型
        value: buffer,
        writeType: 'writeNoResponse',
        success(res) {
          console.log('自学习 writeBLECharacteristicValue success', res.errMsg)
		  //写入如成功？
		 
        },
        fail(error) {
          console.log('fail')
          console.log(error)
		  
          if (error.errCode) {
            uni.showToast({ title: errorCode[error.errCode], icon: 'none' })
          } else if (error.errMsg) {
            uni.showToast({ title: error.errMsg, icon: 'none' })
          } else {
            uni.showToast({ title: 'fail', icon: 'none' })
          }
		  
        },
      })
    },
	//获取蓝牙设备某个服务中的所有 characteristic（特征值）
	getBLEDeviceCharacteristics(){
			var that = this;
		    uni.getBLEDeviceCharacteristics({
		      deviceId: this.deviceInfo.deviceId,
		      serviceId: this.serviceInfo.uuid,
		      success: function (res) {
				  
		        for (let i = 0; i < res.characteristics.length; i++) {
		          let item = res.characteristics[i]
		          if (item.properties.read) { //该特征值是否支持 read 操作
		           
		          }
		          if (item.properties.write) { //该特征值是否支持 write 操作
		           
		
		          }
		          if (item.properties.notify || item.properties.indicate) { //该特征值是否支持 notify或indicate 操作
		       
		            that.notifyBLECharacteristicValueChange();
		          }
		        }
		      }
		    })
	},
	//设置监听
	notifyBLECharacteristicValueChange(){
		 var that = this;
		    uni.notifyBLECharacteristicValueChange({
		      type: "notification",
		      state: true, // 启用 notify 功能
		      deviceId: this.deviceInfo.deviceId,
		      serviceId: this.serviceInfo.uuid,
		      characteristicId: this.notifyCharacteristicsInfo.uuid,
		      success: function (res) {
		      
		        that.onBLECharacteristicValueChange(); //监听特征值变化
				
		      },
		      fail: function (res) {
		        // uni.showToast({
		        //   title: 'notify启动失败',
		        //   mask: true
		        // });
		        // setTimeout(function () {
		        //   uni.hideToast();
		        // }, 2000)
		      }
		    })
	},
	//业务监听
	onBLECharacteristicValueChange(){
		uni.onBLECharacteristicValueChange((res) => {
		  console.log('监听低功耗蓝牙设备的特征值变化', res)
		  // console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
		  // console.log(ab2hex(res.value))
		
		  const value = Array.prototype.map.call(new Uint8Array(res.value), (bit) => bit)
		  console.log(value)
		  this.funReadPage(value)
		})
	}
	
  
  },
}
</script>


<style lang="scss" scoped>
	
	page{
		background: #19253E;
	}
	.setting1{
		.rights{
		   float: right;
		   width: 10px;
		   height: 17px;
		   margin-top:15px;
		   margin-left:15px;
		  
		}
		
		background: #19253E;
		width: 100%;
		float: left;
		.left{
			float: left;
			color: #fff;
		}
		.right{
			float:right;
			 color: #fff;
		}
		// padding-bottom: 100rpx;
		
		.nav_top{
			width: 94%;
			margin-left: 3%;
			heigth:30px;
			color:#979FAE;
			background: #111823;
		}
		
		.nav_menus{
			background: rgba(255,255,255,0.2);;
			margin-top: 7px;
			width:94%;
			margin-left: 3%;
			color: #C0C2C4;
			border-radius: 0.3em;
			.titie_top{
				font-size: 32rpx;
				background: #475165;
				height: 40px;
				line-height: 40px;
				.top_left{
					color:#fff;
					margin-left:3%;
				}
				.top_right{
					margin-right: 3%;
					image{
						margin-top: 10px;;
						width: 20px;
						height: 20px;
						
					}
				}
			}
			.titie_body_line{
				background:rgba(255,255,255,0.2);
				margin-left: 6%;
				width: 88%;
				height: 1rpx;
			}
			.titie_body{
			
				background: #475165;
				height: 50px;
				line-height:50px;
				margin-left: 3%;
				width: 94%;
				
				.titie_body_left{
				
					float: left;
					
				}
				.titie_body_right{
					position: relative;
					top: -50rpx;
					float: right;
					width: 50%;
					view{
						color: #fff;
						height: 44rpx;
						line-height: 44rpx;
						width: 240rpx;
						text-align: center;
						margin-top: 10rpx;
					}
					.right{
						margin-top: 10rpx;
						color: #fff;
						height: 64rpx;
						line-height: 64rpx;
						width: 240rpx;
						text-align: center;
						background: rgba(255,255,255,0.2);
						border-radius: 4px 4px 4px 4px;
						input{
							height: 64rpx;
							line-height: 64rpx;
							color: #fff;
						}
					}
				}
				
				.body_line{
				 margin-left: 3%;
				 width: 94%;
					.left{
						color: #fff;
						float: left;
						input{
							width: 140px;
							background: rgba(255,255,255,0.2);
							height: 30px;
							line-height:30px;
							text-align: center;
							margin-top: 10px;
							margin-right: 3%;;
							color: #fff;
							border-radius: 8rpx;
						}
						.ts{
							height: 35px;
						}
						.ts1{
							height: 30px;
						}
					}
					.right{
						height: 40px;
						float: right;
						input{
							width: 140px;
							background: #545b67;
							height: 30px;
							line-height:30px;
							text-align: center;
							margin-top: 10px;
							margin-right: 3%;;
							color: #fff;
						}
						.evan-switch{
							margin-top: 11px;
						}
						.uv-radio{
							margin-top: 8px;
						}
						.huadong{
							width: 130px;
							margin-top: 18px;
							margin-right: 20px;
							.fonts{
								color:#507afe ;
								font-size: 14px;
								float: right;
								width: 15px;
								text-align: center;
								position: relative;
								top:-33px;
								right: -20px;
							}
						}
						.ts{
							height: 35px;
						}
						.ts1{
							height: 30px;
						}
					}
				}
				
			}
			.titie_body1{
				height: 90px;
			}
		}
		
		.bomt{
			margin-top: 20rpx;
			float: left;
			z-index: 9;
			width:94%;
			margin-left: 3%;
			// position: fixed;
			// padding-top: 20rpx;
			
	
			height: 70rpx;
			line-height: 70rpx;
			margin-bottom: 40rpx;
	
				font-size: 32rpx;
			
			
				text-align: center;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 10rpx;
				background: #507afe;
				color: #fff;
			
		}
	}

</style>
